#include "STC8H.H"
#include "STC8G_H_Delay.h"

#define KEY P3

void MatrixKey_Init()
{
    P0M0 = 0x00;
    P0M1 = 0x00;

	P3M0 = 0x00;
	P3M1 = 0x00;
}

/**
 * @brief Matrix keyboard read code
 * @param NULL
 * @retval KeyNumber The key code value of the pressed key,
 *         if the key is pressed and held, the program will stay in this function,
 *         and the moment the key is released, the key code of the key will be returned.
 *         When no key is pressed, it will return 0
 */
unsigned char MatrixKey()
{
	unsigned char KeyNumber = 0;
	
	P0=0xFF;
	P03=0;
	if(P07==0){delay_ms(20);while(P07==0);delay_ms(20);KeyNumber=1;}
	if(P06==0){delay_ms(20);while(P06==0);delay_ms(20);KeyNumber=2;}
	if(P05==0){delay_ms(20);while(P05==0);delay_ms(20);KeyNumber=3;}
	if(P04==0){delay_ms(20);while(P04==0);delay_ms(20);KeyNumber=4;}
	
	P0=0xFF;
	P02=0;
	if(P07==0){delay_ms(20);while(P07==0);delay_ms(20);KeyNumber=5;}
	if(P06==0){delay_ms(20);while(P06==0);delay_ms(20);KeyNumber=6;}
	if(P05==0){delay_ms(20);while(P05==0);delay_ms(20);KeyNumber=7;}
	if(P04==0){delay_ms(20);while(P04==0);delay_ms(20);KeyNumber=8;}
	
	P0=0xFF;
	P01=0;
	if(P07==0){delay_ms(20);while(P07==0);delay_ms(20);KeyNumber=9;}
	if(P06==0){delay_ms(20);while(P06==0);delay_ms(20);KeyNumber=10;}
	if(P05==0){delay_ms(20);while(P05==0);delay_ms(20);KeyNumber=11;}
	if(P04==0){delay_ms(20);while(P04==0);delay_ms(20);KeyNumber=12;}
	
	P0=0xFF;
	P00=0;
	if(P07==0){delay_ms(20);while(P07==0);delay_ms(20);KeyNumber=13;}
	if(P06==0){delay_ms(20);while(P06==0);delay_ms(20);KeyNumber=14;}
	if(P05==0){delay_ms(20);while(P05==0);delay_ms(20);KeyNumber=15;}
	if(P04==0){delay_ms(20);while(P04==0);delay_ms(20);KeyNumber=16;}

	if(P35==0){delay_ms(20);while(P35==0);delay_ms(20);KeyNumber=20;}
	if(P32==0){delay_ms(20);while(P32==0);delay_ms(20);KeyNumber=21;}
	
	return KeyNumber;
}